import { useEffect, useState } from 'react'
import { StyleSheet, ScrollView, Button, Switch, FlatList, Text, View, TextInput, ActivityIndicator, TouchableOpacity } from 'react-native';
import { useRouter } from 'expo-router'
import { AntDesign, MaterialIcons } from '@expo/vector-icons';

import { Audio } from 'expo-av';
import http from '@/utils/http'
import { debounce } from '@/utils/index'

export default function TabMusic() {
  const [permissionResponse, requestPermission] = Audio.usePermissions();
  const router = useRouter()
  const [musicList, setMusicList] = useState([])
  const [searchText, setSearchText] = useState('')
  const [page, setPage] = useState(1)
  const [refreshing, setRefreshing] = useState(false)
  const [loading, setLoading] = useState(false)
  const [playing, setPlaying] = useState(false)
  const [hasMore, setHasMore] = useState(false)
  const [sounds, setSounds] = useState();
  const [activeIndex, setActiveIndex] = useState(-1)
  const limit = 20
  const ITEM_HEIGHT = 70
  const type = 'qq'

  const viewabilityConfig = {
    waitForInteraction: true,
    itemVisiblePercentThreshold: 75,

  }
  const handleValueChange = (val: boolean) => {
    setIsShow(val)
  }
  useEffect(() => {

  }, [])

  const handleSearch = async (page, searchText) => {
    console.log(`page: ${page}; searchText: ${searchText}`)
    setLoading(true)
    const url = `https://jkyapi.top/API/hqyyid.php?name=${searchText}&type=${type}&page=${page}&limit=${limit}`
    try {
      const res = await http({ url });
      console.log(res)
      if (res && res.code === 1) {
        page === 1 ? setMusicList(res.data) : setMusicList([...musicList, ...res.data])
      } else {
        if (page > 1) {
          setPage(page - 1)
        } else {
          setMusicList([])
        }
        setHasMore(true)
      }
    } catch(err) {
      if (page > 1) {
        setPage(page - 1)
      }
      router.push({ pathname: `/webViewer?uri=${url}` })
    }
    setLoading(false)
  }

  const handleRefresh = debounce(async (text) => {
    setPage(1)
    if (text === undefined) {
      setRefreshing(true)
    }
    await handleSearch(1, text === undefined ? searchText : text)
    setRefreshing(false)
    setHasMore(false)
  }, 50)

  const handleListen = async (item, index) => {
    if (sounds) {
      await sounds.unloadAsync()
    }
    const url = `https://jkyapi.top/API/yyjhss.php?id=${item.id}&type=${item.type}`
    const res = await http({ url });
    if (!res || !res.data.url) return alert('音乐路径为空！');
    setActiveIndex(index)
    const { sound } = await Audio.Sound.createAsync({ uri: res.data.url });
    setSounds(sound);
    await sound.playAsync();
    setPlaying(true)
  }
  
  const handleTogglePlay = async () => {
    if (!sounds) return
    if (playing) {
      await sounds.pauseAsync();
      console.log('停止播放')
      setPlaying(false)
    } else {
      await sounds.playAsync();
      console.log('开始播放')
      setPlaying(true)

    }
  }

  const handleReplay = async () => {
    if (!sounds) return
    await sounds.replayAsync();
  }

  const handleDownload = () => {

  }

  const handleScroll = (a) => {
    // console.log(JSON.stringify(a))
    // console.log('handleScroll')
  }

  const handleEnd = () => {
    if (hasMore || loading || musicList.length === 0) return
    setPage(page + 1)
    handleSearch(page + 1, searchText)
  }

  return (
    <View style={styles.container}>
      <View style={styles.search}>
        <TextInput
          style={styles.input}
          value={searchText}
          placeholder="请输入歌曲搜索关键词"
          onChangeText={(text) => {
            setSearchText(text);
            handleRefresh(text)
          }}
        />
      </View>
      <FlatList
        onEndReachedThreshold={0.5}
        refreshing={refreshing}
        viewabilityConfig={viewabilityConfig}
        data={musicList}
        renderItem={({ item, index }) => <MusicItem item={item} index={index} activeIndex={activeIndex} onListen={handleListen} onDownload={handleDownload} />}
        ListEmptyComponent={<EmptyItem />}
        keyExtractor={item => item.id.toString()}
        onRefresh={handleRefresh}
        onViewableItemsChanged={handleScroll}
        onEndReached={handleEnd}
        ListFooterComponent={<MusicFooter loading={loading} hasMore={hasMore} />}
        ListFooterComponentStyle={styles.loading}
        getItemLayout={(data, index) => ({ length: ITEM_HEIGHT, offset: ITEM_HEIGHT * index, index })}
      />
      <Playground activeIndex={activeIndex} musicList={musicList} playing={playing} onToggle={handleTogglePlay} onReplay={handleReplay} />
    </View>
  );
}

function MusicFooter({ loading, hasMore }) {
  if (hasMore) {
    return <Text style={styles.hasMore}>已加载完毕</Text>
  }
  return (
    loading && <ActivityIndicator size="large" color="#00ff00" />
  )
}

function MusicItem({ item, onListen, onDownload, index, activeIndex }) {
  return (
    <View style={[styles.musicItem, index === activeIndex && styles.activeItem ]}>
      <TouchableOpacity style={styles.musicItemMain} onPress={() => onListen(item, index)}>
        <View>
          <Text style={styles.musicName}>{item.name}</Text>
          <Text style={styles.musicArtist}>{item.artist}</Text>
        </View>
      </TouchableOpacity>
      <Button
        title="下载"
        onPress={() => onDownload(item)}
      />
    </View>
  )
}

function Playground({activeIndex, musicList, playing, onToggle, onReplay}) {
  if (activeIndex < 0 || musicList.length < activeIndex) {
    return (
      <View style={styles.playgound}></View>
    )
  }
  const item = musicList[activeIndex]
  return (
    <View style={styles.playgound}>
      <View style={styles.musicItemMain}>
        <Text style={styles.musicName}>{item.name}</Text>
        <Text style={styles.musicArtist}>{item.artist}</Text>
      </View>
      <TouchableOpacity onPress={() => onToggle(item)}>
        <AntDesign size={24} style={{ marginBottom: -3 }} name={playing ? 'pause' : 'play'} color="black" />
      </TouchableOpacity>
      <TouchableOpacity onPress={() => onReplay(item)}>
        <MaterialIcons size={24} style={{ marginBottom: -3 }} name="replay" color="black" />
      </TouchableOpacity>
    </View>
  )
}

function EmptyItem() {
  return (
    <Text style={styles.empty}>
      什么都没有
    </Text>
  )
}

const styles = StyleSheet.create({
  container: {
    flex: 1
  },
  search: {
    alignItems: 'center',
    flexDirection: 'row',
    paddingHorizontal: 12,
    paddingVertical: 10,
    backgroundColor: '#fff'
  },
  input: {
    flex: 1,
    height: 40,
    paddingLeft: 10,
    backgroundColor: '#f7f8fa'
  },
  musicItem: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingHorizontal: 16,
    paddingVertical: 10,
    borderBottomWidth: 1,
    borderColor: '#ebedf0',
    backgroundColor: '#fff',
    height: 70,
  },
  activeItem: {
    backgroundColor: '#eee'
  },
  playgound: {
    position: 'fixed',
    bottom: 0,
    left: 0,
    width: '100%',
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingHorizontal: 16,
    paddingVertical: 10,
  },
  musicName: {
    fontSize: 14
  },
  musicArtist: {
    fontSize: 12
  },
  musicItemMain: {
    width: '85%'
  },
  empty: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    paddingHorizontal: 12,
    paddingVertical: 10,
    textAlign: 'center'
  },
  hasMore: {
    flexDirection: 'row',
    paddingVertical: 5,
    textAlign: 'center'
  },
  separator: {
    marginVertical: 30,
    height: 1,
    width: '80%',
  },
  loading: {
    paddingVertical: 15
  }
});
 